package com.tao.androidtest;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;


public class Weather extends Activity {

    private EditText inputCity;
    private Button searchBtn;
    private TextView result;
    private String url;
    private static String urlPre = "http://apis.juhe.cn/simpleWeather/query?city=",urlSub = "&key=5493e55b10e39f06963b8d2ad8f84ad1";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_report);
        this.init();
    }

    private void init() {
        this.inputCity = findViewById(R.id.cityNameText);
        this.searchBtn = findViewById(R.id.searchCityWeather);
        this.result = findViewById(R.id.weatherSearchResult);

        searchBtn.setOnClickListener(v -> {
            getRequest();
        });

    }

    private void getRequest() {
        new Thread(() -> {
            url = urlPre+inputCity.getText().toString()+urlSub;//韶关
            System.out.println(url);
            HttpURLConnection conn = null;
            try {
                URL requestUrl = new URL(this.url);
                conn = (HttpURLConnection) requestUrl.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if(HttpURLConnection.HTTP_OK==conn.getResponseCode()){
                    InputStream in=conn.getInputStream();
                    String backContent = getStringFromInputStream(in);
                    in.close();
                    System.out.println(backContent);
                    result.setText(backContent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).run();
    }

    private String getStringFromInputStream(InputStream in) throws IOException {
        Reader reader = new InputStreamReader(in,"UTF-8");
        BufferedReader br = new BufferedReader(reader,512);
        StringBuilder sb = new StringBuilder();
        int value;
        while ((value = br.read()) != -1) {
            sb.append((char)value);
        }
        return sb.toString();
    }
}
